package com.icehelper.hades.base.log;

import org.slf4j.MDC;

import java.util.HashMap;
import java.util.Map;
/**
 * @author Leon Sun
 */
public class LogUtil {

    public static String genTraceId() {
        String traceId = TraceIdGenerator.generatorTraceId();
        setTraceId(traceId);
        return traceId;
    }

    public static String genSpanId() {
        String spanId = SpanIdGenerator.generatorSpanId();
        setSpanId(spanId);
        return spanId;
    }

    public static String getTraceId() {
        return MDC.get(LogConstant.KEY_TRACE_ID);
    }

    public static void setTraceId(String traceId) {
        MDC.put(LogConstant.KEY_TRACE_ID, traceId);
    }

    public static String getSpanId() {
        return MDC.get(LogConstant.KEY_SPAN_ID);
    }

    public static void setSpanId(String spanId) {
        MDC.put(LogConstant.KEY_SPAN_ID, spanId);
    }

    public static void setUri(String uri) {
        MDC.put(LogConstant.KEY_URI, uri);
    }

    public static String getUri() {
        return MDC.get(LogConstant.KEY_URI);
    }

    public static void removeTraceId() {
        MDC.remove(LogConstant.KEY_TRACE_ID);
    }

    public static void removeSpanId() {
        MDC.remove(LogConstant.KEY_SPAN_ID);
    }

    public static void removeUri() {
        MDC.remove(LogConstant.KEY_URI);
    }

    public static void setHintCode(Long hintCode) {
        if (hintCode == null) {
            hintCode = 0L;
        }
        MDC.put(LogConstant.KEY_HINT_CODE, hintCode.toString());
    }

    public static String getHintCode() {
        return MDC.get(LogConstant.KEY_HINT_CODE);
    }

    public static void removeHintCode() {
        MDC.remove(LogConstant.KEY_HINT_CODE);
    }

    public static void setHintContent(String content) {
        MDC.put(LogConstant.HEADER_HINT_CONTENT, content);
    }

    public static String getHintContent() {
        return MDC.get(LogConstant.KEY_HINT_CONTENT);
    }

    public static void removeHintContent() {
        MDC.remove(LogConstant.KEY_HINT_CONTENT);
    }

    public static void addKVs(Map<String, String> kvs) {
        if (!kvs.isEmpty()) {
            Map<String, String> map = new HashMap<>(kvs.size());
            kvs.forEach((k, v) -> map.put(k, v == null ? "" : String.valueOf(v)));
            kvs.forEach((k, v) -> MDC.put(k, v));
        }
    }

    public static void setDlTag(String dlTag) {
        MDC.put(LogConstant.KEY_DL_TAG, dlTag);
    }

}
